<?php
require_once dirname(__FILE__) . '/includes/common.inc.php';
require_once dirname(__FILE__) . "/database/$database/database.inc.php";

header('Content-Type: text/plain');

global $myManager;

try {
  $hostname = HOST_NAME;
  $username = USER_NAME2;
  $password = PASSWORD2;
  $dbname = DATABASE_NAME2;
  $myPdo = new PDO ('mysql:host=' . $hostname, $username, $password);
  $myPdo->exec('USE ' . $dbname);
  $myPdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
  echo $e->getMessage ();
}


//$orm1 = classToOrm('produceselect');
try {
  $stmt = $myPdo->prepare("SELECT p.e_oid AS id, p.trackId as trackId, 
                                  i.e_oid AS pid
                           FROM ns_Produce AS p LEFT JOIN ns__ez_relation_produce_producepurchaseitem AS pi ON (p.e_oid = pi.oid_a AND pi.var_a = 'purchaseitem') 
                                                LEFT JOIN ns_ProducePurchaseItem AS i ON i.e_oid = pi.oid_b
                          ");
  $stmt->execute();
  
  //$myManager->start_t();
  $myPdo->beginTransaction();
  $i = 0;
  
  while ($i < $stmt->rowCount()) {
    $produce = $stmt->fetch(PDO::FETCH_OBJ);
    
    $sql1 = " SELECT DISTINCT ppis.e_oid as id, ppis.trackId as trackId, 
                              ppis.title as title, ppis.value as value
              FROM ns_ProducePurchaseItemSelect AS ppis LEFT JOIN ns__ez_relation_producepurchaseitem_producepurchaseitemselect AS rpis ON ppis.e_oid = rpis.oid_b where rpis.oid_a = $produce->pid 
              ";
    $stmt1 = $myPdo->prepare($sql1);
    $stmt1->execute();
    $m = 0;
    while ($m < $stmt1->rowCount()) {
      $tmp1 = $stmt1->fetch(PDO::FETCH_OBJ);
      $sql2 = "INSERT INTO ns_ProduceSelect (trackId, produce_trackId, title, value) VALUES ('$tmp1->trackId', '$produce->trackId', '$tmp1->title', '$tmp1->value')";
      $myPdo->exec($sql2);
      $m++;
    }
    $i++;
  }
  $myPdo->commit();
  echo json_encode(array());
} catch (PDOException $e) {
  $myPdo->rollBack();
  echo $e->getMessage();
}
?>